package com.huayun.util.utils;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Description:一些工具类
 * Created on 2018/11/27 0027 17:19:02
 * author:Ahuangshang
 */
////////////////////////////////////////////////////////////////////
//                          _ooOoo_                               //
//                         o8888888o                              //
//                         88" . "88                              //
//                         (| ^_^ |)                              //
//                         O\  =  /O                              //
//                      ____/`---'\____                           //
//                    .'  \\|     |//  `.                         //
//                   /  \\|||  :  |||//  \                        //
//                  /  _||||| -:- |||||-  \                       //
//                  |   | \\\  -  /// |   |                       //
//                  | \_|  ''\---/''  |   |                       //
//                  \  .-\__  `-`  ___/-. /                       //
//                ___`. .'  /--.--\  `. . ___                     //
//              ."" '<  `.___\_<|>_/___.'  >'"".                  //
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
//            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
//      ========`-.____`-.___\_____/___.-`____.-'========         //
//                           `=---='                              //
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
//                  佛祖保佑       永不宕机     永无BUG             //
////////////////////////////////////////////////////////////////////
public class Utils {
    public static boolean isNull(Object obj) {
        if (obj == null)
            return true;

        if (obj instanceof CharSequence)
            return ((CharSequence) obj).length() == 0;

        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();

        if (obj instanceof Map)
            return ((Map) obj).isEmpty();

        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNull(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }

    public static boolean notNull(Object obj) {
        return !isNull(obj);
    }

    public static boolean isJsonString(String str) {
        boolean isJsonStr;
        try {
            JSONObject jsonObject = new JSONObject(str);
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            isJsonStr = false;
        }
        try {
            JSONArray jsonArray = new JSONArray(str);
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            isJsonStr = false;
        }
        return isJsonStr;
    }

    /**
     * 将json格式的字符串解析成Map对象 <li>
     * json格式：{"name":"admin","retries":"3fff","testname"
     * :"ddd","testretries":"fffffffff"}
     */
    public static <T> HashMap<String, T> jsonToMap(String json) {
        // 将json字符串转换成jsonObject
        JSONObject jsonObject = null;
        HashMap<String, T> hashMap = new HashMap<>();
        try {
            jsonObject = new JSONObject(json);
            Iterator it = jsonObject.keys();
            // 遍历jsonObject数据，添加到Map对象
            String key;
            Object value;
            while (it.hasNext()) {
                key = String.valueOf(it.next());
                value = jsonObject.get(key);
                if (isNull(hashMap)) {
                    hashMap = new HashMap<>();
                }
                hashMap.put(key, (T) value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return hashMap;
    }

    /**
     * 将Map转换成Json
     *
     */
    public static String mapToJson(Map<String, Object> jsonMap) throws Exception {
        StringBuilder result = new StringBuilder();
        result.append("{");
        Iterator<Map.Entry<String, Object>> entryIterator = jsonMap.entrySet().iterator();
        for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Map) {
                System.out.println("\n Object Key : " + key);
                String mapJson = mapToJson((Map<String, Object>) value);
                result.append("\"").append(key).append("\":").append(mapJson);
            } else {
                Gson gson = new Gson();
                String json = gson.toJson(value);
                result.append("\"").append(key).append("\":").append(json);
            }
            // 最后一个去掉 逗号
            entryIterator.next();
            if (entryIterator.hasNext()) {
                result.append(",");
            }
        }
        result.append("}");
        return result.toString();
    }

    public static String unicodeToChinese(String dataStr) {
        final StringBuilder buffer = new StringBuilder();
        Pattern p = Pattern.compile("\\\\u([\\S]{4})([^\\\\]*)");
        Matcher match = p.matcher(dataStr);
        if (match.find()) {
            while (match.find()) {
                char letter = (char) Integer.parseInt(match.group(1), 16);
                buffer.append(Character.toString(letter));
                buffer.append(match.group(2));
            }
        } else {
            buffer.append(dataStr);
        }

        return buffer.toString();
    }
}
